package vip.wangwenhao.autoconfigure.oauth2;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import vip.wangwenhao.common.enums.ResultCode;
import vip.wangwenhao.common.result.Result;
import vip.wangwenhao.common.util.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangwenhao
 */
@Slf4j
public class CustomAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException ae) throws IOException, ServletException {
        Throwable cause = ae.getCause();
        log.error("", ae);
        Result result;
        if (cause instanceof InvalidTokenException || cause instanceof InsufficientAuthenticationException) {
            result = Result.fail(ResultCode.INVALID_TOKEN);
        } else if (ae instanceof InsufficientAuthenticationException) {
            result = Result.fail(ResultCode.UNAUTHORIZED_REQUEST, ae.getMessage());
        } else {
            result = Result.fail(ResultCode.UN_LOGIN);
        }
        HttpUtils.response(response, HttpStatus.SC_UNAUTHORIZED, result);
    }
}